<?php

namespace app\api\controller;

use think\Controller;
use think\Db;
use think\Log;
use think\Request;

class Account extends Controller
{
    
    protected $table_user_sms_info= 'user_sms_info';      /* 验证码信息表 */
    protected $table_user_bind_info= 'user_bind_info';    /* 绑定手机号 */
    protected $table_accounts_info= 'accounts_info';    /* 账号表 */
    
    protected function Db_connect_user_sms_info(){
        $user_sms_info= Db::connect('db_qpplatformdb')->table($this->table_user_sms_info);
        return $user_sms_info;
    }
    
    protected function Db_connect_user_bind_info(){
        $user_bind_info= Db::connect('db_config2')->table($this->table_user_bind_info);
        return $user_bind_info;
    }
    
    
    protected function Db_connect_table_accounts_info(){
        $accounts_info= Db::connect('db_config2')->table($this->table_accounts_info);
        return $accounts_info;
    }

    public function __construct()
    {
        parent::__construct();
        set_cors();
    }
    
    
    /**重置密码
     * @return mixed
     * @throws \Exception
     */
    public function resetPwd(){
        $pwd = trim(input('pwd'));
        $phone = input('phone');
        $code = input('code');
    
        if(empty($pwd) or empty($phone) or empty($code)){
            Log::error('param empty');
            puterror('param empty');
        }
        
        // 是否过期
        $where['Phone'] = $phone;
        $where['type'] = 4;
        $where['status'] = 0;// 未使用状态
        $row = $this->Db_connect_user_sms_info()->where($where)->order('ID desc')->find();
        
        if(!$row){
            puterror('请核对手机号和验证码后重新尝试！');
        }

        if(strtotime($row['ExpireTime']) < time()){
            puterror('验证码已过期，请重新获取！');
        }

        if($row['Code'] != $code){
            puterror('请输入一个正确的验证码！');
        }

        // 验证码标记为已经使用状态
        $this->Db_connect_user_sms_info()->where('ID',$row['ID'])->update(['status'=>1]);
    
        // 查询手机号对应的账号
        $UserID = $this->Db_connect_user_bind_info()->where('Phone',$phone)->value('UserID');
        try {
            $res = $this->Db_connect_table_accounts_info()->where('UserID',$UserID)->update(['LoginPass'=>$pwd]);
            mylog(000);
            if($res === false){
                mylog('resetPwd');
                puterror('未知异常1');
            }
        }catch (\Exception $e){
            mylog($e->getMessage());
            puterror('未知异常2');
        }

        putsuccess('恭喜您，重置密码成功！');
    }
    
    /**更换手机号
     * @return mixed
     * @throws \Exception
     */
    public function changePhone(){
        $oldphone = trim(input('oldphone'));
        $newphone = trim(input('newphone'));
        $code = trim(input('code'));
        $pwd = trim(input('pwd'));

        if(empty($newphone)){
            // 验证原手机号
            if(empty($oldphone) or empty($code)){
                Log::error('param empty');
                puterror('param empty');
            }
    
            // 是否过期
            $where['phone'] = $oldphone;
            $where['type'] = 5;
            $where['status'] = 0;// 未使用状态
    
            $row = $this->Db_connect_user_sms_info()->where($where)->order('ID desc')->find();
    
            if(!$row){
                puterror('请核对手机号和验证码后重新尝试！');
            }
    
            if(strtotime($row['ExpireTime']) < time()){
                puterror('验证码已过期，请重新获取！');
            }
    
            if($row['Code'] != $code){
                puterror('请输入一个正确的验证码！');
            }
    
            // 验证码标记为已经使用状态
            $this->Db_connect_user_sms_info()->where('ID',$row['ID'])->update(['status'=>1]);
    
            putsuccess('原手机号正确！');
        }else{
            // 验证新手机号 且写库
            if(empty($oldphone) or empty($newphone) or empty($code)){
                Log::error('param empty');
                puterror('param empty');
            }
    
            // 是否过期
            $where['phone'] = $newphone;
            $where['type'] = 6;
            $where['status'] = 0;// 未使用状态
    
            $row = $this->Db_connect_user_sms_info()->where($where)->order('ID desc')->find();
            if(!$row){
                puterror('请核对手机号和验证码后重新尝试！');
            }
    
            if(strtotime($row['ExpireTime']) < time()){
                puterror('验证码已过期，请重新获取！');
            }
    
            if($row['Code'] != $code){
                puterror('请输入一个正确的验证码！');
            }
    
            // 验证码标记为已经使用状态
            $this->Db_connect_user_sms_info()->where('ID',$row['ID'])->update(['status'=>1]);
    
            // 查询手机号对应的账号
            $res = $this->Db_connect_user_bind_info()->where('Phone',$oldphone)->update(['Phone'=>$newphone]);
            if($res === false){
                Log::error('changePhone');
                puterror('changePhone');
            }

            // 如果传来了密码 就直接重置密码
            if(!empty($pwd)){
                $UserID = $this->Db_connect_user_bind_info()->where('Phone',$newphone)->value('UserID');
                $this->Db_connect_table_accounts_info()->where('UserID',$UserID)->update(['LoginPass'=>$pwd]);
            }

            putsuccess('恭喜您，手机号修改成功！');
        }
    }

    // 金科发送统计
    public function send_data(){
        $get = input('get.');

        $res = request_post('https://www.shileke.cn/api/lySdkUser/setUser',$get);
        putsuccess($res);
    }

    public function getKey(){
        $get = request()->get();
    
        $user_game_info = Db::connect('db_config2')->table('user_game_info')->where(['UserID'=>$get['user_id']])->find();
        if(empty($user_game_info['CustomizationKey'])){
            exit(json_encode(['code'=>0,'msg'=>'']));
        }else{
            exit(json_encode(['code'=>1,'msg'=>$user_game_info['CustomizationKey']]));
        }
    }
    
    public function key(){
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段
        $get = request()->get();

        $CustomizationKey = Db::connect('db_config2')->table('user_game_info')->where(['CustomizationKey'=>$get['key']])->find();
        if($CustomizationKey){
            exit(json_encode(['code'=>-1,'msg'=>'秘钥重复']));
        }

        $user_game_info = Db::connect('db_config2')->table('user_game_info')->where(['UserID'=>$get['user_id']])->find();
        if(!$user_game_info){
            exit(json_encode(['code'=>0,'msg'=>'未找到该用户绑定信息']));
        }

        if(empty($user_game_info['CustomizationKey'])){
            Db::connect('db_config2')->table('user_game_info')->where(['UserID'=>$get['user_id']])->update(['CustomizationKey'=>$get['key']]);
            exit(json_encode(['code'=>1,'msg'=>$get['key']]));
        }else{
            exit(json_encode(['code'=>2,'msg'=>$user_game_info['CustomizationKey']]));
        }
    }

    public function getIsChangeBinding(){
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段

        $get = request()->get();
    
        $user_game_info = Db::connect('db_config2')->table('user_game_info')->where(['UserID'=>$get['user_id']])->find();
        if(empty($user_game_info)){
            exit(json_encode(['code'=>0,'IsChangeBinding'=>'']));
        }else{
            exit(json_encode(['code'=>1,'IsChangeBinding'=>$user_game_info['IsChangeBinding']]));
        }
    }

    //更换UniqueID
    public function updateUniqueID(){
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段

        $get = request()->get();
        mylog($get);
        $key = Db::connect('db_config2')->table('user_game_info')->where(['CustomizationKey'=>$get['key']])->find();
        if(!$key){
            exit(json_encode(['code'=>0,'msg'=>'未找到改秘钥']));
        }
        //当前用户id
        $dUserID = Db::connect('db_config2')->table('accounts_info')->where(['UserID'=>$get['UserID']])->find();
        
        //秘钥对应的id
        $kUserID = Db::connect('db_config2')->table('accounts_info')->where(['UserID'=>$key['UserID']])->find();

        //更换操作
        if(empty($dUserID) || empty($kUserID)){
            exit(json_encode(['code'=>-1,'msg'=>'用户为未找到']));
        }
        try{
            Db::startTrans();
            

            //UniqueID 是唯一索引 先更新一个
            Db::connect('db_config2')->table('accounts_info')->where(['UserID'=>$dUserID['UserID']])->update(['UniqueID'=>time()]);

            Db::connect('db_config2')->table('accounts_info')->where(['UserID'=>$kUserID['UserID']])->update(['UniqueID'=>$dUserID['UniqueID']]);

            Db::connect('db_config2')->table('accounts_info')->where(['UserID'=>$dUserID['UserID']])->update(['UniqueID'=>$kUserID['UniqueID']]);

            //不允许再次换绑
            Db::connect('db_config2')->table('user_game_info')->where(['UserID'=>$kUserID['UserID']])->update(['IsChangeBinding'=>1]);
            Db::connect('db_config2')->table('user_game_info')->where(['UserID'=>$dUserID['UserID']])->update(['IsChangeBinding'=>1]);

            Db::commit();    
            exit(json_encode(['code'=>1,'msg'=>'绑定成功']));
        } catch (\Exception $e) {
            Db::rollback();
            exit($this->success('绑定失败'));
        }

       


    }

    public function boardInfo(Request $request){
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段
        $param = $request->param();

        Db::connect('db_qpplatformdb')->table('user_board_info')->insert([
            'UserID'=>0,
            'Message'=>$param['info'],
        ]);
        exit('true');
    }
}

